package com.zzyl.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.serve.domain.NursingTask;
import com.zzyl.serve.dto.NursingTaskDto;
import com.zzyl.serve.mapper.NursingTaskMapper;
import com.zzyl.serve.service.INursingTaskService;
import com.zzyl.serve.vo.NursingTaskResponse;
import com.zzyl.serve.vo.NursingTaskVo;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.zzyl.common.utils.SecurityUtils.getLoginUser;

/**
 * 护理任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-06
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private ICheckInService checkInService;


    /**
     * 查询护理任务列表
     *
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTaskVo> selectNursingTaskList(NursingTask nursingTask) {
        List<NursingTask> nursingTasks = nursingTaskMapper.selectNursingTaskList(nursingTask);
        List<NursingTaskVo> nursingTaskVos = nursingTasks.stream().map(nursingTask1 -> {
            NursingTaskVo nursingTaskVo = new NursingTaskVo();
            BeanUtil.copyProperties(nursingTask1, nursingTaskVo);
            // 如果 nursingId 不为空且不为 ""
            if (nursingTask1.getNursingId() != null && !nursingTask1.getNursingId().isEmpty()) {
                // 将 nursingId 拆分为多个ID
                String[] nursingIds = nursingTask1.getNursingId().split(",");
                List<String> nursingNames = new ArrayList<>();

                for (String nursingId : nursingIds) {
                    try {
                        // 获取每个护理员的名称
                        String nursingName = sysUserMapper.getUserNameByNursingId(Long.valueOf(nursingId));
                        if (nursingName != null) {
                            nursingNames.add(nursingName);
                        }
                    } catch (NumberFormatException e) {
                        // 如果 nursingId 不是有效数字，则忽略
                        continue;
                    }
                }
                // 设置 nursingName 属性
                nursingTaskVo.setNursingName(nursingNames);
            } else {
                // 如果 nursingId 为空或为 ""，设置为空列表
                nursingTaskVo.setNursingName(new ArrayList<>());
            }
            return nursingTaskVo;
        }).collect(Collectors.toList());
        return nursingTaskVos;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask)
    {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 查询护理任务详细信息
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskResponse selectNursingTaskById(Long id) {
        NursingTask nursingTaskdetail = getById(id);
        NursingTaskResponse nursingTaskResponse = new NursingTaskResponse();
        BeanUtil.copyProperties(nursingTaskdetail, nursingTaskResponse);
        String updateBy =nursingTaskdetail.getUpdateBy();
        if (StringUtils.isNotEmpty(updateBy)){
            String userName = sysUserMapper.getUserNameByNursingId(Long.valueOf(nursingTaskdetail.getUpdateBy()));
            nursingTaskResponse.setUpdater(userName);
        }
        String[] nursingIds = nursingTaskdetail.getNursingId().split(",");
        List<String> nursingNames = new ArrayList<>();
        for (String nursingId : nursingIds) {
            try {
                String nursingName = sysUserMapper.getUserNameByNursingId(Long.valueOf(nursingId));
                if (nursingName != null) {
                    nursingNames.add(nursingName);
                }
            } catch (NumberFormatException e) {
                continue;
            }
        }
        nursingTaskResponse.setNursingName(nursingNames.toArray(new String[0]));
        Elder elder = elderMapper.selectElderById(nursingTaskdetail.getElderId());
        String idCardNo = elder.getIdCardNo();
        String year = idCardNo.substring(6, 10);
        //与当前年份计算年龄
        int birthYear = Integer.parseInt(year);
        int now = LocalDate.now().getYear();
        nursingTaskResponse.setAge(now - birthYear);
        char sexChar = idCardNo.charAt(16); // 第 17 位（索引为 16）
        String sex = (sexChar % 2 == 0) ? "女" : "男";
        nursingTaskResponse.setSex(sex);
        CheckIn checkIn = checkInService.getOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, nursingTaskdetail.getElderId()));
        nursingTaskResponse.setNursingLevelName(checkIn.getNursingLevelName());
        return nursingTaskResponse;
    }

    /**
     * 取消护理任务
     */
    @Override
    public int cancelPlan(NursingTaskDto dto) {

        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        String updateId = String.valueOf(userId);
        String updateName = loginUser.getUser().getNickName();

        NursingTask nursingTask = new NursingTask();
        nursingTask.setId(dto.getTaskId());
        nursingTask.setCancelReason(dto.getReason());
        nursingTask.setStatus(3);
        nursingTask.setUpdateBy(updateId);
        nursingTask.setUpdateBy(updateName);
        nursingTask.setUpdateTime(DateUtils.getNowDate());
        return nursingTaskMapper.cancelPlan(nursingTask);

    }
    /**
     * 执行护理任务
     */
    @Override
    public int doPlan(NursingTaskDto dto) {
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        String updateId = String.valueOf(userId);
        String updateName = loginUser.getUser().getNickName();

        NursingTask nursingTask = new NursingTask();
        nursingTask.setId(dto.getTaskId());
        nursingTask.setRealServerTime(dto.getRealServerTime());
        nursingTask.setMark(dto.getMark());
        nursingTask.setStatus(2);
        nursingTask.setTaskImage(dto.getTaskImage());
        nursingTask.setUpdateBy(updateId);
        nursingTask.setNickName(updateName);
        nursingTask.setUpdateTime(DateUtils.getNowDate());
        return nursingTaskMapper.doPlan(nursingTask);
    }
    /**
     * 护理任务改期
     */
    @Override
    public int changePlanTime(NursingTaskDto dto) {
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUserId();
        String updateId = String.valueOf(userId);
        String updateName = loginUser.getUser().getNickName();

        NursingTask nursingTask = new NursingTask();
        nursingTask.setId(dto.getTaskId());
        nursingTask.setEstimatedServerTime(dto.getEstimatedServerTime());
        nursingTask.setUpdateBy(updateId);
        nursingTask.setNickName(updateName);
        nursingTask.setUpdateTime(DateUtils.getNowDate());
        return nursingTaskMapper.changePlanTime(nursingTask);
    }
}
